<template>
  <div>
    <PageTitleSearch
      :title="title"
      :hotelList="hotelList"
      :currentHotel="currentHotel"
      v-model:lastMonth="lastMonth"
      :currentAcc="currentAcc"
      @hotel-change="handleSelectChange"
      @date-change="handleDateSelect"
      @acc-change="handleAccSelect"
    />

    <!-- 主体内容区域  -->
    <div class="main-content">
      <a-row>
        <a-col :span="20">
          <FlexCard :loading="loading" title="服务效率">
            <a-row>
              <a-col :span="8">
                <a-row>
                  <!-- <a-col :span="12"></a-col> -->
                  <a-col class="col-title" :span="12">FTE前厅人服比</a-col>
                </a-row>
                <a-row>
                  <!-- <ProgressBar :dataList="dataListFront" :showLabel="true" :max="maxValue" /> -->
                </a-row>
              </a-col>
              <a-col :span="4">
                <a-row class="col-title">FTE客房人服比</a-row>
                <a-row>
                  <!-- <ProgressBar :dataList="dataListRoom" :showLabel="false" :max="maxValue" /> -->
                </a-row>
              </a-col>
              <a-col :span="4">
                <a-row class="col-title">FTE餐饮人服比</a-row>
                <a-row>
                  <!-- <ProgressBar :dataList="dataListRest" :showLabel="false" :max="maxValue" /> -->
                </a-row>
              </a-col>
              <a-col :span="4">
                <a-row class="col-title">FTE餐饮厨房人服比</a-row>
                <a-row>
                  <!-- <ProgressBar :dataList="dataListKitchen" :showLabel="false" :max="maxValue" /> -->
                </a-row>
              </a-col>
              <a-col :span="4">
                <a-row class="col-title">FTE总人服比</a-row>
                <a-row>
                  <!-- <ProgressBar :dataList="dataListOverall" :showLabel="false" :max="maxValue" /> -->
                </a-row>
              </a-col>
            </a-row>
          </FlexCard>
        </a-col>
      </a-row>
      <ReportRemarkCard class="remark-height" :loading="loading" v-if="reportCode" title="说明" :reportCode="reportCode" :reportName="reportName" />
    </div>
  </div>
</template>

<script>
  import ReportRemarkCard from '@/views/applications/ui/ReportRemarkCard.vue';
  import * as MathUtil from '/@/utils/MathUtil';
  import dayjs from 'dayjs';
  import { defHttp } from '/@/utils/http/axios';
  // import ProgressBar from '@/views/applications/ui/ProgressBar.vue';
  import FlexCard from '@/views/applications/ui/FlexCard.vue';
  import PageTitleSearch from '@/views/applications/ui/PageTitleSearch.vue';
  const INCOME_APIS = {
    month: 'getHotelMonthReportEff',
    year: 'getHotelMonthReportAccEff',
  };

  const REPORT_NAME = '服务效率（本级）';
  const REPORT_CODE = 'hotel-month-reporteff';

  export default {
    name: REPORT_NAME,

    components: {
      ReportRemarkCard,
      // ProgressBar,
      FlexCard,
      PageTitleSearch,
    },

    data() {
      return {
        title: '服务效率',
        reportCode: '',
        reportName: '',
        loading: false,
        lastMonth: dayjs().subtract(1, 'month').format('YYYYMM'),
        accList: [
          { label: '当月', value: 'month' },
          { label: '当年', value: 'year' },
        ],
        currentAcc: 'month',
        hotelList: [],
        currentHotels: [],
        dataListFront: [],
        dataListRoom: [],
        dataListRest: [],
        dataListKitchen: [],
        dataListOverall: [],
        maxValue: 400,
      };
    },

    created() {
      defHttp.get({ url: '/data/hotel/list' }, { isTransformResponse: false }).then((res) => {
        if (res.success && res.result.length > 0) {
          this.hotelList = res.result.map((s) => {
            return { label: s.name, key: s.code };
          });
          this.currentHotels = res.result.map((d) => d.code);
          const accName = this.accList.find((a) => a.value === this.currentAcc).label;
          this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.lastMonth}`;
          this.reportName = `${REPORT_NAME}-${accName}-${this.lastMonth}`;
          this.fetchData();
        }
      });
    },

    methods: {
      handleDateSelect(date) {
        this.lastMonth = date;
        // 更新reportCode和reportName
        const accName = this.accList.find((a) => a.value === this.currentAcc).label;
        this.reportCode = `${REPORT_CODE}-${this.currentAcc}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${accName}-${this.lastMonth}`;
        this.fetchData();
      },

      handleAccSelect(value) {
        this.currentAcc = value;
        // 更新reportCode和reportName
        const accName = this.accList.find((a) => a.value === value).label;
        this.reportCode = `${REPORT_CODE}-${value}-${this.lastMonth}`;
        this.reportName = `${REPORT_NAME}-${accName}-${this.lastMonth}`;
        this.fetchData();
      },

      handleTreeSelect() {
        if (!this.currentHotels.length) return;
        this.fetchData();
      },

      isMonthDisabled(current) {
        // 获取上个月的最后一天
        const lastMonth = dayjs().subtract(1, 'month').endOf('month');
        // 限制选择范围在上个月及之前
        return current && current > lastMonth;
      },
      fetchData() {
        this.loading = true;
        defHttp
          .post({
            url: 'data/query',
            data: {
              labelCode: INCOME_APIS[this.currentAcc],
              sqlParams: [
                { key: 'code', value: this.currentHotels.join(',') },
                { key: 'month', value: this.lastMonth },
              ],
              pageIndex: 1,
              pageSize: 1000,
            },
          })
          .then((res) => {
            const dataList = res.datas.success ? res.datas.data : [];
            this.computeFteData(dataList);
            this.loading = false;
          });
      },
      computeFteData(dataList) {
        if (!dataList || !dataList.length) {
          this.dataListFront = [];
          this.dataListRoom = [];
          this.dataListRest = [];
          this.dataListKitchen = [];
          return;
        }
        const acc = dataList.reduce(
          (acc, item) => {
            acc.frontFte += item.frontFte;
            acc.roomFte += item.roomFte;
            acc.restFte += item.restFte;
            acc.kitchenFte += item.kitchenFte;
            acc.fte += item.fte;
            acc.dinners += item.dinners;
            acc.income += item.income;
            acc.guests += item.guests;
            acc.sroom += item.sroom;
            acc.roomIncome += item.roomIncome;
            return acc;
          },
          {
            frontFte: 0,
            roomFte: 0,
            restFte: 0,
            kitchenFte: 0,
            fte: 0,
            dinners: 0,
            income: 0,
            guests: 0,
            sroom: 0,
            roomIncome: 0,
          }
        );
        const accAvg = this.wrapData({ ...acc, hotelShortName: '平均值' });
        const rows = dataList.map((item) => {
          return this.wrapData(item);
        });
        console.log('rows', rows);
        this.dataListFront = [
          { name: accAvg.hotelName, value: accAvg.frontRatio },
          ...rows.map((i) => ({
            name: i.hotelName,
            value: i.frontRatio,
          })),
        ];
        this.dataListRoom = [
          { name: accAvg.hotelName, value: accAvg.roomRatio },
          ...rows.map((i) => ({
            name: i.hotelName,
            value: i.roomRatio,
          })),
        ];
        this.dataListRest = [
          { name: accAvg.hotelName, value: accAvg.restRatio },
          ...rows.map((i) => ({
            name: i.hotelName,
            value: i.restRatio,
          })),
        ];
        this.dataListKitchen = [
          { name: accAvg.hotelName, value: accAvg.kitchenRatio },
          ...rows.map((i) => ({
            name: i.hotelName,
            value: i.kitchenRatio,
          })),
        ];
        this.dataListOverall = [
          { name: accAvg.hotelName, value: accAvg.overallRatio },
          ...rows.map((i) => ({
            name: i.hotelName,
            value: i.overallRatio,
          })),
        ];
        this.maxValue = Math.max(
          ...this.dataListFront.map((i) => i.value),
          ...this.dataListRoom.map((i) => i.value),
          ...this.dataListRest.map((i) => i.value),
          ...this.dataListKitchen.map((i) => i.value)
        );
      },
      wrapData(data) {
        const guests = data.guests;
        const sroom = data.sroom;
        const dinners = data.dinners;
        const frontFte = data.frontFte;
        const roomFte = data.roomFte;
        const restFte = data.restFte;
        const kitchenFte = data.kitchenFte;
        const fte = data.fte;
        const frontRatio = MathUtil.safeDivide(guests, frontFte);
        const roomRatio = MathUtil.safeDivide(sroom, roomFte);
        const restRatio = MathUtil.safeDivide(dinners, restFte);
        const kitchenRatio = MathUtil.safeDivide(dinners, kitchenFte);
        const overallRaw = guests + dinners;
        const overallRatio = MathUtil.safeDivide(overallRaw, fte);
        return {
          hotelName: data.hotelShortName,
          frontRatio,
          roomRatio,
          restRatio,
          kitchenRatio,
          overallRatio,
        };
      },
    },
  };
</script>

<style lang="less" scoped>
  @media @desktop {
    .main-content {
      padding: 12px 0;
      height: 1000px;
    }

    .col-title {
      font-size: 15px;
      text-align: center;
    }
    .remark-height {
      height: 1000px;
    }
    .ruler-row {
      margin-top: 20px;
      padding-top: 0;
      padding-bottom: 25px;
    }
    .echarts {
      width: 100%;
      height: 860px;
    }
    .extra-sel {
      display: flex;
      justify-content: flex-end;
    }
    .select-title-space {
      width: 120px;
      margin-right: 20px;
    }
    .select-tree-title {
      width: 200px;
    }
  }
</style>
